<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="编码" prop="coded">
        <!-- <el-select v-model="queryParams.areaId" clearable placeholder="请选择学校区域" @change="selectSchoolArea">
          <el-option
            v-for="item in areaOptions"
            :key="item.coded"
            :label="item.name"
            :value="item.coded"
            @keyup.enter.native="handleQuery"
            >
          </el-option>
           @keyup.enter.native="handleQuery"   @keyup.enter.native="handleQuery"
        </el-select> -->
        <el-input
          v-model="queryParams.coded"
          placeholder="请输入学校编码"
          clearable
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" clearable placeholder="请先选择类型">
          <el-option
            v-for="item in typeOptions"
            :key="item.id"
            :label="item.label"
            :value="item.id"
            >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学校名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入学校名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['admin:school:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['admin:school:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['admin:school:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入</el-button>
        <!--  v-hasPermi="['admin:school:export']" -->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="schoolList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="所属区域" align="center" prop="areaName" />
      <el-table-column label="学校类型" align="center" prop="typeStr" />
      <el-table-column label="学校名称" align="center" prop="name" width="300"/>
      <el-table-column label="学校编码" align="center" prop="coded" />
      <el-table-column label="计划人数" align="center" prop="plan" />
      <el-table-column label="报名状态" align="center" prop="statusStr" />
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['admin:school:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['admin:school:remove']"
          >删除</el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学校对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学校名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入学校名称" />
        </el-form-item>
        <el-form-item label="学校编码" prop="coded">
          <el-input v-model="form.coded" placeholder="请输入学校编码" />
        </el-form-item>
        <el-form-item label="学校区域" prop="areaId">
          <!-- <el-input v-model="form.areaId" placeholder="请输入学校区域" /> -->
          <el-select v-model="form.areaId" clearable placeholder="请选择学校区域" @change="selectSchoolArea">
            <el-option
              v-for="item in areaOptions"
              :key="item.coded"
              :label="item.name"
              :value="item.coded"
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="type">
          <el-select v-model="form.type" clearable placeholder="请选择类型">
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="计划人数" prop="plan">
          <!-- <el-input v-model="form.plan" placeholder="请输入计划人数" /> -->
          <el-input-number v-model="form.plan" label="描述文字"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <!-- <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" /> -->
          <el-switch
            v-model="form.status"
            active-color="#13ce66"
            inactive-color="#ff4949"

            >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
     <!-- 导入学校 -->
     <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
          <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport + '&warehouseId=' + queryParams.initCkIdParm"
            :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
            :auto-upload="false" drag v-loading="scrkloading">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div> -->
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                @click="importTemplate">下载模板</el-link>
            </div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFileForm" v-if="!btnUploadFlag">确 定</el-button>
            <el-button type="info" @click="submitFileForm" v-else="btnUploadFlag">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </el-dialog>
  </div>
</template>

<script>
import {getContentArea } from "@/api/admin/content";
import { listSchool, getSchool, delSchool, addSchool, updateSchool,getSchoolArea } from "@/api/admin/school";
import { getToken } from "@/utils/auth";
export default {
  name: "School",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学校表格数据
      schoolList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        coded: null,
        areaId: null,
        type: null,
        plan: null,
        status: null,
        initCkIdParm: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {

      },
      areaOptions:[],
      schoolAreaOptions:[],
      // 学校导入参数
      upload: {
        // 是否显示弹出层（库存导入）
        open: false,
        // 弹出层标题（（库存导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 入库导入地址
        url: process.env.VUE_APP_BASE_API + "/admin/school/importSchoolData",

      },
      // 加载Loding
      scrkloading: false,
        // 上传入库按钮状态
      btnUploadFlag: false,
      //类型
      typeOptions:[
        {id:1,label:'公办'},
        {id:2,label:'民办'},


      ],

    };
  },

  created() {
    this.getAreaFun();
    this.getList();




  },

  methods: {
    // 查询区域下拉框
    getAreaFun(){
        getContentArea().then(response => {
            // console.log('学校管理--查询区域下拉框',response)
            if(response.code == 200){
                this.areaOptions = response.data;

                // this.getSchoolAreaFun('');
            }
        });
    },
    getSchoolAreaFun(areaId){
      getSchoolArea(areaId).then(response => {
            // console.log('学校管理--查询学校数据下拉框',response)
            if(response.code == 200){
                this.schoolAreaOptions = response.data;
                // console.log('-----this.schoolList---this.schoolAreaOptions',this.schoolList)
            }
        });
     },
     /** 查询学校列表 */
    getList() {
      this.loading = true;
      listSchool(this.queryParams).then(response => {
        console.log('---查询学校列表response',response)
        this.schoolList = response.rows;

        this.schoolList.forEach(element => {
          // 处理列表数据学校区域
          this.areaOptions.forEach(items=>{
              // console.log('items',items)
              if(items.coded == element.areaId){
                element.areaName = items.name;

              }
          })
          // 处理学校类型
          if(element.type == 1){
            element.typeStr = '公办';
          }else if(element.type == 2){
            element.typeStr = '民办';
          }else{
            element.typeStr = '未定义';
          }
          //     <!--  0=停止报名，1=可以报名-->
          if(element.status == 0){
            element.statusStr = '停止报名';
          }else if(element.status == 1){
            element.statusStr = '可以报名';
          }
        });


        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        coded: null,
        areaId: null,
        type: null,
        plan: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学校";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {

      this.reset();
      const id = row.id || this.ids
      getSchool(id).then(response => {
        console.log('----修改的数据',response)
        if(response.data.status == 1){
          response.data.status = true;
        }else if(response.data.status == 0){
          response.data.status = false;
        }
        this.form = response.data;
        this.open = true;
        this.title = "修改学校";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log('----this.form',this.form)
      if(this.form.status){
        this.form.status = 1;
      }else{
        this.form.status = 0;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSchool(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSchool(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除学校编号为"' + ids + '"的数据项？').then(function() {
        return delSchool(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    selectSchoolArea(e){
      console.log('----e'.e)
      let areaIdStr = e.toString()
      console.log('----areaIdStr',typeof areaIdStr)
      this.getSchoolAreaFun(areaIdStr)
    },
    handleImport() {
      this.upload.title = "入库导入";
      this.upload.open = true;
    },
    /** 下载导入入库数据表模板操作 */
    importTemplate() {
      this.download('/admin/school/schoolDataTemplate', {
      }, `导入学校数据表_${new Date().getTime()}.xlsx`)
    },
    // 文件上传成功处理

    handleFileUploadProgress(event, file, fileList) {
      console.log('文件上传中处理', event)
      this.upload.isUploading = true;
      // this.uploadCkdr.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList(this.queryParams);
    },
    // 提交上传文件
    submitFileForm() {
      this.scrkloading = true;
      this.btnUploadFlag = true;
      setTimeout(() => {

        this.$refs.upload.submit();
        this.btnUploadFlag = false;
        this.scrkloading = false;
      }, 1500);

    },

  }
};
</script>
